<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px; position: relative;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add">新建</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">客户</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ detailsTitle }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100%;">

        <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
        <div style="height: auto; width: 65%; overflow-y: auto; margin-right: 10px;">
          <el-card style="box-shadow: none;">
            <el-form :model="cusForm" style="width: 100%;">
              <el-form-item label="" prop="cusName">
                <el-input v-model="cusForm.cusName"
                  style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                  class="idoo-details-input" placeholder="编码客户名称：例如：阿里巴巴集团控股有限公司"></el-input>
              </el-form-item>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="客户类型">
                    <el-select v-model="cusForm.cusType" placeholder="请选择客户类型" style="width: 70%;"
                      class="idoo-details-select">
                      <el-option v-for="item in codeStore().getSystemCode('CRM_CUS_TYPE') as CodeValueType[]"
                        :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="客户行业">
                    <el-input v-model="cusForm.cusIndustry" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：消费、金融、制造业、食品加工..."></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户职位">
                    <el-input v-model="cusForm.cusPosition" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：销售经理、总经理、董事长、文员..."></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="客户等级">
                    <el-rate v-model="cusForm.cusLevel" size="large" style="width: 100%;" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户规模">
                    <el-select v-model="cusForm.cusScale" placeholder="请选择客户规模" style="width: 70%;"
                      class="idoo-details-select">
                      <el-option v-for="item in codeStore().getSystemCode('CRM_CUS_SCALE') as CodeValueType[]"
                        :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="电话">
                    <el-input v-model="cusForm.cusPhone" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：18742536182 、 0432-2762558"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱">
                    <el-input v-model="cusForm.cusEmail" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：1750276460@qq.com"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="地址">
                    <el-input v-model="cusForm.cusAddress" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：浙江省杭州市滨江区网商路699号1号楼5楼"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户官网">
                    <el-input v-model="cusForm.cusWeburl" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：https://www.alibaba.com/"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="客户来源">
                    <el-input v-model="cusForm.cusSource" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：销售、个人、中介"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </div>

        <!-- 右侧：修改记录区域，保持背景色 -->
        <div style="width: 35%; padding: 5px; overflow-y: auto;" v-if="formId">
          <!-- 按钮行 -->
          <div style="display: flex;margin-bottom: 10px;">
            <el-button :icon="Edit" :class="recordRemark ? 'idoo-details-add' : 'el-button-primary'"
              :type="recordRemark ? 'primary' : ''" @click="recordRemarkChoose"></el-button>
            <el-button :icon="Search" :class="recordSearch ? 'idoo-details-add' : 'el-button-primary'"
              :type="recordSearch ? 'primary' : ''" @click="recordSearchChoose"></el-button>

            <el-input ref="searchRef" v-if="recordSearch" v-model="recordSearchInfo" placeholder="搜索：操作记录内容：操作人/字段名称/内容"
              style="margin-left: 50px;width:60%">
              <template #append>
                <el-button :icon="Search" @click="recordSearching" style="display:inherit !important;" />
              </template>
            </el-input>
          </div>
          <div v-if="recordRemark">
            <el-input type="textarea" v-model="recordRemarkInfo" class="record-remark-textarea"
              placeholder="记录详情内部说明..." style="width: 70%;"></el-input>
          </div>
          <div style="margin-top: 5px;" v-if="recordRemark">
            <el-button type="primary" @click="sendRecordRemark" size="large"
              style="width: 60px; height: 35px; font-size: small;">发送</el-button>
          </div>
          <!-- 操作记录组件 -->
          <CustomerRecord :recordInfos="recordInfos" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled, RefreshLeft, Edit, Search } from '@element-plus/icons-vue';
import router from '@/router';
import { ElMessageBox } from 'element-plus';
import { codeStore } from '@/stores/codeStore';
import { _getCustomerInfo, _getRecordInfos, _modifyCustomerInfo, _saveCustomerInfo, _saveRecordRemarkInfos, _searchRecordRemarkInfos } from '@/api/generic/customer/list-api';
import type { CustomerFrom } from '@/types/customer/types';
import type { CodeValueType } from '@/types/piniatypes';
import { getChangedFields, updateWrapperBuilder } from '@/utils/form/updateFormHelper';
import type { BaseRecordVo } from '@/types/basetypes';
import CustomerRecord from '@/components/base/record/IdooRecord.vue';
const route = useRoute();
const detailsTitle = ref("");
const isFormChanged = ref(false);
let formId = route.query.id || "";
const recordInfos = ref<BaseRecordVo[]>([]);
const recordRemark = ref(false);
const recordRemarkInfo = ref("");
const recordSearch = ref(false);
const recordSearchInfo = ref("");
const searchRef = ref(null);

// 初始化表单数据
const cusForm = ref<CustomerFrom>({
  cusName: '', //客户名称
  cusType: '', //客户类型
  cusIndustry: '', //客户行业
  cusPosition: '', //客户置为
  cusLevel: '0', //客户等级
  cusPhone: '', //电话
  cusEmail: '', //邮箱
  cusAddress: '', //地址
  cusScale: '', //企业规模
  cusWeburl: '', //官网
  cusSource: '', //客户来源
})
const originalFormData = ref<CustomerFrom>({});
originalFormData.value = JSON.parse(JSON.stringify(cusForm.value));
console.log("create", cusForm.value, originalFormData.value)

const recordRemarkChoose = () => {
  recordRemark.value = !recordRemark.value;
  if (recordRemark.value) {
    nextTick(() => {
      const textarea = document.querySelector('.el-textarea__inner') as HTMLTextAreaElement;
      textarea.focus();
    });
  }
}

const recordSearchChoose = () => {
  recordSearch.value = !recordSearch.value;
  console.log("2")
  console.log(recordSearch.value)
  if (recordSearch.value) {
    nextTick(() => {
      if (searchRef.value) {
        const a = searchRef.value as HTMLTextAreaElement;
        a.focus();
      }
    });
  }
}

const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(cusForm.value));
  detailsTitle.value = cusForm.value.cusName || '新建';
  isFormChanged.value = false;
}

// 监听表单变化
watch(() => cusForm.value, (newVal) => {
  console.log(cusForm.value);
  console.log(originalFormData.value)
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

//初始化加载数据
onMounted(async () => {
  console.log("onMounted", cusForm.value)
  // originalFormData.value = JSON.parse(JSON.stringify(cusForm.value));
  console.log(originalFormData.value)
  detailsTitle.value = '新建'
  //获取用户数据
  if (formId) {
    //编辑
    const res = await _getCustomerInfo({ id: formId.toString() });
    if (res.code === 200 && res.data) {
      cusForm.value = res.data;
      originalFormData.value = JSON.parse(JSON.stringify(res.data));
      detailsTitle.value = cusForm.value.cusName || '';
    }
    const rres = await _getRecordInfos({ id: formId.toString() });
    console.log(rres.code);
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
  }
  console.log("onMounted", cusForm.value)
});
//返回按钮
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).catch(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    console.log( route.fullPath)
    console.log( route.fullPath.replace('/add', ''))
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
//发送备注消息
const sendRecordRemark = async () => {
  if (formId && recordRemark.value) {
    await _saveRecordRemarkInfos({
      bizId: formId.toString(),
      remark: recordRemarkInfo.value.toString(),
    })
    //刷新操作记录
    const rres = await _getRecordInfos({ id: formId.toString() });
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
    recordRemarkInfo.value = '';
  }
}
//搜索备注内容
const recordSearching = async () => {
  if (formId && recordSearch.value) {
    const ress = await _searchRecordRemarkInfos({
      _search_bizid: formId.toString(),
      _search_content: recordSearchInfo.value
    })
    if (ress.code === 200 && ress.data) {
      recordInfos.value = ress.data;
    }
  }
}
// 保存处理函数
const handleSave = async () => {
  //TODO 表单校验
  const formData = cusForm.value
  try {
    const i = getChangedFields(originalFormData.value, formData)
    console.log(i);
    let res;
    if (formId) {
      const upWrap = updateWrapperBuilder(formData, i); // 传递 formData 作为参数
      res = await _modifyCustomerInfo(upWrap); // 使用 upWrap 作为参数
    } else {
      res = await _saveCustomerInfo(formData);
      if (res.code === 200 && res.data) {
        formId = res.data[0];
        console.error(formId)
        cusForm.value.id = formId;
      }
    }
    if (res && res.code === 200) {
      resetForm();
      //刷新操作记录
      const rres = await _getRecordInfos({ id: formId.toString() });
      console.log(rres.code);
      if (rres.code === 200 && rres.data) {
        recordInfos.value = rres.data;
      }
    }
  } catch (error) {
    console.error('保存失败:', error);
  }
};

// 撤销修改，还原表单
const handleRevert = () => {
  cusForm.value = JSON.parse(JSON.stringify(originalFormData.value));
};
</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}
</style>
